import * as API_Search from '../../api/search'

var app = getApp()
Page({
  data: {
    historyKeyword: [],     // 历史搜索
    searchType:'',      // 搜索类型
    showSearchType: false, // 是否显示搜索类型
    autoCompleteData: '',    // 自动补全数据
    hotKeyword: [],         // 热门搜索词
    keyword:'',
    scrollBodyHeight:'100%',
    topNum:'',
    source:''//来源
  },
  //取消搜索
  closeSearch: function () {wx.navigateBack()},
  //清除搜索关键字
  clearKeyword: function () {
    this.setData({keyword: ''});
  },
  onLoad: function (options) {
    this.getSearchKeyword();
    this.initCentHeight();
    this.setData({source:options.source})
  },
  initCentHeight:function(){
    let that=this;
    let query = wx.createSelectorQuery();
    query.select('.container').boundingClientRect();
          query.exec(function (res) {
            
            let height=res[0].height*getApp().globalData.ratio;
            let statusBarHeight=getApp().globalData.statusBarHeight;
            let navHeight=getApp().globalData.navHeight;
           
            let scrollBodyHeight=height-navHeight-statusBarHeight;
            //获取以上元素节点高度
            // let centerHeight = res[0].height * ratio;
            // let centerTopHeight = res[1].height * ratio;
            //计算出scroll_body节点的高度
            // let scrollBodyHeight = centerHeight - centerTopHeight;
            //传递数据，赋值
            that.setData({
              scrollBodyHeight: scrollBodyHeight+"rpx",
              topNum:navHeight+statusBarHeight+"rpx"
            });
        })
  },

  onShow(){
    let arr = wx.getStorageSync('searchData');
    if (arr.length==0){
      wx.setStorageSync('searchData', [])
    }
    this.setData({historyKeyword:wx.getStorageSync('searchData')})
    this.setData({keyword:''})
  },
  //自动补全数据事件
  handleOnSubmit(e) {
    let keyword = e.currentTarget.dataset.keyword
    // this.getSearchResult(keyword)
    this.handleSearchHistory(keyword)
  },
  //热门搜索
  getSearchKeyword() {
    API_Search.getHotKeywords().then((data=>{
      this.setData({ hotKeyword: data })
    }))
  },
  inputChange: function (e) {
    this.setData({keyword: e.detail.value || ''});
    // this.getSearchKeyword()
  },
  inputFocus: function () {
    this.getSearchKeyword();
  },
  //搜索类型
  isShowSearchType(){this.setData({showSearchType:!this.data.showSearchType})},
  //清除历史搜索
  clearHistory: function () {
    this.setData({historyKeyword: []})
    wx.clearStorageSync('searchData')
  },
  //历史记录，热门搜索事件
  onKeywordTap: function (event) {
    let keyword = event.currentTarget.dataset.keyword
    this.getSearchResult(keyword.searchValue || keyword.hot_name)
    this.handleSearchHistory(keyword.searchValue || keyword.hot_name)
  },
  //搜索结果
  getSearchResult(keyword) {
    //首页来的
    if(this.data.source){
      wx.navigateTo({ url: '/pages/productList/productList?searchKey=' + keyword || '' })
    }else{
      let pages = getCurrentPages();//当前页面
      let prevPage = pages[pages.length-2];//上一页面
      prevPage.setData({//直接给上移页面赋值
        productList:[],
        'params.searchValue':keyword,
        'params.pageNum':1
      });
      prevPage.flushList()
      wx.navigateBack({//返回
        delta:1
      })
    }

  },
  //选择搜索的历史
  onKeywordConfirm(event) {
    let keyword = event.detail.value;
    this.getSearchResult(keyword);
    this.handleSearchHistory(keyword)
  },
  // 存储历史搜索记录
  handleSearchHistory(keyword) {
    let searchData = this.data.historyKeyword;
    if (keyword == undefined || keyword == '') return;
    for (let i = 0; i < searchData.length; i++) {
      let _index = searchData[i].searchValue.indexOf(keyword)
      if (_index !== -1) {
        // 删除已存在后重新插入至数组
        searchData.splice(i, 1)
      } else if (searchData.length > 9) {
        // 只保留10个
        searchData.pop();
      }
    }
    searchData.unshift({
      searchValue: keyword,
      id: searchData.length
    });
    wx.setStorageSync('searchData', searchData);
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
